package com.dehui.traders.ui.optioanl;

import android.app.ProgressDialog;
import android.content.Context;
import android.databinding.ObservableArrayList;
import android.databinding.ObservableField;
import android.databinding.ObservableInt;
import android.databinding.ObservableList;
import android.text.TextUtils;
import android.view.View;

import com.dehui.traders.R;
import com.dehui.traders.ui.optioanl.adapter.OptionalStockAdapter;
import com.dehui.traders.bean.BaseListResponse;
import com.dehui.traders.bean.BaseResponse;
import com.dehui.traders.bean.OptionalCodeRank;
import com.dehui.traders.bean.RealtimeQuote;
import com.dehui.traders.bean.SeachHistory;
import com.dehui.traders.bean.SearchCodeResult;
import com.dehui.traders.config.Preferences;
import com.dehui.traders.service.CallListener;
import com.dehui.traders.service.NetImpl;
import com.dehui.traders.ui.stockdetail.StocksDetailActivity;
import com.dehui.traders.utils.DialogHelp;
import com.dehui.traders.utils.UserHelp;
import com.dehui.traders.widgets.CommonAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.ToastUtils;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by hqq on 18.4.18.
 */

public class AddOptionalStockViewModel extends BaseViewModel implements OptionalStockAdapter.OnOptionalStockAdapterListener {

    public AddOptionalInterface addOptionalInterface;
    private AddOptionalStockActivity activity;
    public ObservableList<SearchCodeResult> stockBeanObservableList = new ObservableArrayList<>();
    public ObservableList<SearchCodeResult> historysObserableList = new ObservableArrayList<>();
    public ObservableInt recentlyTitleVisity = new ObservableInt(View.VISIBLE);

    public OptionalStockAdapter stockAdapter = new OptionalStockAdapter(context,stockBeanObservableList,R.layout.list_item_add_optional_stock);

    public ObservableField<CommonAdapter> stockObservable = new ObservableField<>(stockAdapter);

    public BindingCommand cancelOnClick = new BindingCommand(()->{
        if (addOptionalInterface != null)
            addOptionalInterface.finishView();
    });

    public BindingCommand clearHistoryOnClick = new BindingCommand(()->{
        Preferences.saveSeachCodeList("");
        historysObserableList.clear();
        stockBeanObservableList.clear();
        stockAdapter.notifyDataSetChanged();
    });
    private ProgressDialog loadingDialog;

    public AddOptionalStockViewModel(Context context, AddOptionalInterface addOptionalInterface, AddOptionalStockActivity activity) {
        super(context);
        this.addOptionalInterface = addOptionalInterface;
        this.activity = activity;
        init();
    }

    private void init() {
        stockAdapter.setListener(this);
        getHistory();
    }

    private void getHistory() {
        String seachCodes = Preferences.getSeachCodeList();
        if (!TextUtils.isEmpty(seachCodes)){
            SeachHistory history = new Gson().fromJson(seachCodes, SeachHistory.class);
            if (history != null){
                historysObserableList.clear();
                historysObserableList.addAll(history.codes);
                stockBeanObservableList.clear();
                stockBeanObservableList.addAll(historysObserableList);
                stockAdapter.notifyDataSetChanged();
            }
        }
    }

    public void searchStock(String str) {
        Call<BaseListResponse<SearchCodeResult>> call = NetImpl.searchCodeAndName(str);
        call.enqueue(new CallListener<BaseListResponse<SearchCodeResult>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<SearchCodeResult>> response) {
                BaseListResponse<SearchCodeResult> body = response.body();
                if (body.status == 200){
                    recentlyTitleVisity.set(View.GONE);
                    List<SearchCodeResult> codeResults = body.result;
                    stockBeanObservableList.clear();
                    for (SearchCodeResult item : codeResults){
                        if ("sh".equals(item.market) || "sz".equals(item.market))
                            stockBeanObservableList.add(item);
                    }
                    stockAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void _onFailure() {

            }
        });
    }

    @Override
    public void addStock(SearchCodeResult item) {
        if (!UserHelp.getIsLogin(context))
                return;
        saveHistory(item);
        Call<BaseResponse<String>> call = NetImpl.saveCode(item.code, item.market, UserHelp.getUserId(), "0", item.name, "0");
        call.enqueue(new CallListener<BaseResponse<String>>() {
            @Override
            public void _onResponse(Response<BaseResponse<String>> response) {
                BaseResponse<String> baseResponse = response.body();
                if (baseResponse.status == 200){
                    ToastUtils.showShort(R.string.add_success);
                    updateOptionCode(item.name,item.code,item.market);
                    stockAdapter.notifyDataSetChanged();
                }else{
                    ToastUtils.showShort(R.string.add_failed);
                }
            }

            @Override
            public void _onFailure() {
                ToastUtils.showShort(R.string.add_failed);
            }
        });
    }

    private void updateOptionCode(String name, String code, String market) {
        String myOpitonCode = Preferences.getMyOpitonCode();
        List<OptionalCodeRank> codeList = null;
        try {
            codeList =new Gson().fromJson(myOpitonCode, new TypeToken<List<OptionalCodeRank>>() {}.getType());
        }catch (Exception e){
            codeList = new ArrayList<>();
        }

        codeList.add(0,new OptionalCodeRank(name,code,market,0));
        String codestr = new Gson().toJson(codeList);
        Preferences.saveMyOpitonCode(codestr);
    }

    private void saveHistory(SearchCodeResult item) {
        for (int i = 0; i < historysObserableList.size(); i++){
            SearchCodeResult result = historysObserableList.get(i);
            if (result.code.equals(item.code)){
                historysObserableList.remove(i);
                break;
            }
        }
        historysObserableList.add(0,item);
        SeachHistory seachHistory = new SeachHistory(historysObserableList);
        Preferences.saveSeachCodeList(new Gson().toJson(seachHistory));
    }

    public void onClickItem(int position) {
        SearchCodeResult codeResult = stockBeanObservableList.get(position);
        saveHistory(codeResult);
        loadingDialog = DialogHelp.getLoadingDialog(context);
        loadingDialog.show();
        List<OptionalCodeRank> list = new ArrayList<>();
        list.add(new OptionalCodeRank(codeResult.name,codeResult.code,codeResult.market,0));
        Call<BaseListResponse<RealtimeQuote>> call = NetImpl.getRealtimeQuote(list);
        call.enqueue(new CallListener<BaseListResponse<RealtimeQuote>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<RealtimeQuote>> response) {
                loadingDialog.dismiss();
                BaseListResponse<RealtimeQuote> realtimeQuoteBaseListResponse = response.body();
                if (realtimeQuoteBaseListResponse.status == 200){
                    List<RealtimeQuote> quotes = realtimeQuoteBaseListResponse.result;
                    RealtimeQuote realtimeQuote = quotes.get(0);
                    StocksDetailActivity.start(activity,"搜索",realtimeQuote.name,realtimeQuote.code,
                            String.valueOf(realtimeQuote.closePrice),codeResult.market);
                }
            }

            @Override
            public void _onFailure() {
                loadingDialog.dismiss();
            }
        });
    }

    public void refreshAdapter() {
        stockAdapter.notifyDataSetChanged();
    }

    public interface AddOptionalInterface{
        void finishView();
    }


}
